import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:flutter_svg/svg.dart';
import 'package:hippo_app/models/plant.dart';
import 'package:hippo_app/values/app_value.dart';
import 'package:hippo_app/values/color_value.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:hippo_app/values/size_value.dart';
import 'package:hippo_app/values/style_value.dart';
import 'package:hippo_app/widgets/app_header/app_header.dart';
import 'package:hippo_app/widgets/app_scaffold/app_scaffold.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});


  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List<Plant> dataList = [];
  final ScrollController scrollController = ScrollController();
  final TextEditingController searchController = TextEditingController();

  bool searchBarSuffixIconVisible = false;

  void getDataList() {
    List<Plant> list = [];
    for (int i = 0; i < 10; i++) {
      list.add(
        Plant(
          id: i.toString(),
          name: "重瓣粉色康乃馨$i",
          waterTotal: i,
          fertilizerTotal: i,
        ),
      );
    }

    setState(() {
      dataList = list;
    });
  }

  @override
  void initState() {
    super.initState();
    scrollController.addListener(() {
      double scrollOffsetY = scrollController.position.pixels;
      double scrollContentHeight = scrollController.position.maxScrollExtent;
      if (scrollOffsetY > scrollContentHeight + 20) {
        getDataList();
      }
    });
    getDataList();
  }

  @override
  void dispose() {
    super.dispose();
  }

  toPage(Plant plant) {
    Navigator.pushNamed(context, '/plantView', arguments: plant);
  }

  Widget buildHeaderCard() {
    return AppHeader(
      height: SizeValue.appBarLargeHeight,
      borderRadius: StyleValue.appBarLargeBorderRadius,
      appBar: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            AppLocalizations.of(context)!.homeTitle,
            style: StyleValue.appBarTitleStyle,
          ),

          IconButton(
            padding: EdgeInsets.symmetric(vertical: 0, horizontal: 0),
            icon: Icon(
              CupertinoIcons.arrow_2_circlepath,
              size: SizeValue.appActionIconSize,
              color: Colors.white,
            ),
            onPressed: () {},
          ),
        ],
      ),
      child: Column(children: [buildSearch(), buildTotalCard()]),
      //child: Positioned(child: buildSearch(), buildTotalCard()),
    );
  }

  Widget buildTotalCardItem(
    String total,
    String img,
    TextStyle totalStyle,
    String totalLabel,
    TextStyle totalLabelStyle,
  ) {
    return Expanded(
      child: SizedBox(
        height: 82,
        child: Column(
          children: [
            Container(
              margin: EdgeInsets.only(top: 10, bottom: 0),
              width: 28,
              height: 28,
              child: SvgPicture.asset(img),
            ),
            Text(total, style: totalStyle),
            Text(totalLabel, style: totalLabelStyle),
          ],
        ),
      ),
    );
  }

  Widget buildTotalCard() {
    return Container(
      margin: EdgeInsets.only(
        top: SizeValue.appContentPadding / 2,
        bottom: SizeValue.appContentPadding / 2,
        left: SizeValue.appContentPadding,
        right: SizeValue.appContentPadding,
      ),
      decoration: BoxDecoration(
        boxShadow: [StyleValue.defaultCardBoxShadow],
        border: Border.all(color: Colors.white, width: 0.8),
        gradient: StyleValue.homePlantCardLinearGradient,
        borderRadius: BorderRadius.all(Radius.circular(SizeValue.appBorderRadius)),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          buildTotalCardItem(
            "10",
            "assets/images/home/home_plant.svg",
            StyleValue.homeCardPlantTotalStyle,
            AppLocalizations.of(context)!.plantTotalLabel,
            StyleValue.homeCardTotalLabelStyle,
          ),
          buildTotalCardItem(
            "999",
            "assets/images/home/home_water.svg",
            StyleValue.homeCardWaterTotalStyle,
            AppLocalizations.of(context)!.plantWaterTotalLabel,
            StyleValue.homeCardTotalLabelStyle,
          ),
          buildTotalCardItem(
            "999",
            "assets/images/home/home_fertilizer.svg",
            StyleValue.homeCardFertilizerTotalStyle,
            AppLocalizations.of(context)!.plantFertilizerTotalLabel,
            StyleValue.homeCardTotalLabelStyle,
          ),
        ],
      ),
    );
  }

  Widget buildSearch() {
    return Container(
      margin: EdgeInsets.only(
        top: 0,
        left: SizeValue.appContentPadding,
        right: SizeValue.appContentPadding,
        bottom: SizeValue.appContentPadding,
      ),
      height: 36,
      decoration: BoxDecoration(
        color: ColorValue.homeSearchBarBg,
        borderRadius: BorderRadius.all(Radius.circular(50)),
      ),
      child: TextField(
        controller: searchController,
        onChanged: (value) {
          setState(() {
            searchBarSuffixIconVisible = value.isNotEmpty;
          });
        },
        maxLines: 1,
        style: StyleValue.homeSearchStyle,
        decoration: InputDecoration(
          contentPadding: EdgeInsets.symmetric(vertical: 0, horizontal: 0),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.all(Radius.circular(50)),
            borderSide: BorderSide(color: Colors.transparent, width: 0),
          ),
          enabledBorder: OutlineInputBorder(
            borderRadius: BorderRadius.all(Radius.circular(50)),
            borderSide: BorderSide(color: Colors.transparent, width: 0),
          ),
          focusedBorder: OutlineInputBorder(
            borderRadius: BorderRadius.all(Radius.circular(50)),
            borderSide: BorderSide(color: Colors.transparent, width: 0),
          ),
          hintText: AppLocalizations.of(context)!.homeSearchBarHintText,
          prefixIcon: Icon(Icons.search, size: 22),
          suffixIcon:
              searchBarSuffixIconVisible
                  ? IconButton(
                    padding: EdgeInsets.symmetric(vertical: 0, horizontal: 0),
                    icon: Icon(Icons.clear, size: 20, color: Colors.grey),
                    onPressed: () {
                      setState(() {
                        searchBarSuffixIconVisible = false;
                      });
                      searchController.clear();
                    },
                  )
                  : null,
        ),
      ),
    );
  }

  Widget buildListCard(BuildContext context, int index) {
    return Container(
      decoration: BoxDecoration(
        border: Border.all(color: Colors.white, width: 0.5),
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(SizeValue.appBorderRadius)),
        boxShadow: [StyleValue.defaultCardBoxShadow],
      ),
      padding: EdgeInsets.all(8),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          InkWell(
            onTap: () {
              toPage(dataList[index]);
            },
            child: Container(
              margin: EdgeInsets.only(bottom: 10),
              decoration: BoxDecoration(
                color: ColorValue.appImgBg,
                borderRadius: BorderRadius.all(Radius.circular(SizeValue.appBorderRadius)),
              ),
              child: ClipRRect(
                borderRadius: BorderRadius.all(Radius.circular(SizeValue.appBorderRadius)),
                child: Image.asset(
                  height: 145,
                  width:
                      MediaQuery.of(context).size.width / 2 -
                      SizeValue.appContentPadding * 3,
                  index % 2 == 0
                      ? 'assets/images/demo2.jpg'
                      : 'assets/images/demo.jpg',
                  fit: BoxFit.cover,
                  //fit: BoxFit.fill,
                ),
              ),
            ),
          ),
          Text(
            dataList[index].name ?? '-',
            style: StyleValue.homeListItemNameStyle,
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
          Container(
            margin: EdgeInsets.only(top: 6, bottom: 6),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  "${AppLocalizations.of(context)!.plantWaterTotalSimpleLabel}:${dataList[index].waterTotal ?? 0}",
                  style: StyleValue.homeListItemTotalStyle,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
                Container(
                  margin: EdgeInsets.only(bottom: 1),
                  width: 18,
                  height: 18,
                  child: OutlinedButton(
                    style: OutlinedButton.styleFrom(
                      padding: EdgeInsets.symmetric(vertical: 0, horizontal: 0),
                      minimumSize: Size(18, 18),
                      maximumSize: Size(18, 18),
                      foregroundColor: Colors.white,
                      backgroundColor: ColorValue.appPrimaryColor,
                      side: BorderSide(
                        color: ColorValue.appPrimaryColor,
                        width: 0.5,
                      ),
                    ),
                    onPressed: () {},
                    child: Icon(Icons.add),
                  ),
                ),
              ],
            ),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                "${AppLocalizations.of(context)!.plantFertilizerTotalSimpleLabel}:${dataList[index].fertilizerTotal ?? 0}",
                style: StyleValue.homeListItemTotalStyle,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
              Container(
                margin: EdgeInsets.only(top: 1),
                width: 18,
                height: 18,
                child: OutlinedButton(
                  style: OutlinedButton.styleFrom(
                    padding: EdgeInsets.symmetric(vertical: 0, horizontal: 0),
                    minimumSize: Size(18, 18),
                    maximumSize: Size(18, 18),
                    foregroundColor: ColorValue.appPrimaryColor,
                    backgroundColor: Colors.transparent,
                    side: BorderSide(
                      color: ColorValue.appPrimaryColor,
                      width: 0.5,
                    ),
                  ),
                  onPressed: () {},
                  child: Icon(Icons.add),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget buildList() {
    return Expanded(
      child: Container(
        margin: EdgeInsets.only(
          top: SizeValue.appContentPadding / 2,
          left: SizeValue.appContentPadding,
          right: SizeValue.appContentPadding,
          bottom: 0,
        ),
        child: MediaQuery.removePadding(
          removeTop: true,
          context: context,
          child: StaggeredGridView.countBuilder(
            shrinkWrap: true,
            controller: scrollController,
            crossAxisCount: 4,
            crossAxisSpacing: SizeValue.appContentPadding,
            mainAxisSpacing: SizeValue.appContentPadding,
            itemCount: dataList.length,
            itemBuilder: (context, index) {
              return buildListCard(context, index);
            },
            staggeredTileBuilder: (index) => StaggeredTile.count(2, 2.925),
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return AppScaffold(
      body: Column(children: [buildHeaderCard(), buildList()]),
    );
  }
}
